package com.hk.core.authentication.security.authentication.sms;

import com.hk.commons.util.AssertUtils;
import com.hk.core.authentication.api.UserPrincipal;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.function.Function;

/**
 * 短信验证 Provider
 *
 * @author kevin
 * @date 2018-07-26 16:41
 */
public record SMSAuthenticationProvider(
        Function<String, UserPrincipal> authenticationFunction) implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        var token = (SMSAuthenticationToken) authentication;
        var principal = authenticationFunction.apply(token.getPrincipal().toString());
        AssertUtils.notNull(principal, "principal Must not be null.");
        var authenticationToken = new SMSAuthenticationToken(principal, null);
        authenticationToken.setDetails(token.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SMSAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
